package com.elitel.frame.business.service.impl;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import com.elitel.frame.main.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.elitel.base.variable.RabbitMQRoutingKey;
import com.elitel.common.exception.BaseException;
//import com.elitel.common.redis.service.RedisCacheService;
import com.elitel.frame.base.component.RedisCacheProjectService;
import com.elitel.frame.base.component.RedisCacheTreeConfig;
import com.elitel.frame.base.component.RedisCatchBasicServer;
import com.elitel.frame.base.component.exportprojectdata.DataBaseConnInfo;
import com.elitel.frame.business.dao.ext.ExecuteSqlMapper;
import com.elitel.frame.business.service.TreeConfigService;
import com.elitel.frame.main.dao.CfgDbMapper;
import com.elitel.frame.main.dao.CfgExttreeMapper;
import com.elitel.frame.main.dao.CfgFieldMapper;
import com.elitel.frame.main.dao.CfgTableMapper;
import com.elitel.frame.main.dao.SysPrjserviceMapper;
import com.elitel.frame.main.dao.ext.ExtBaseQueryfieldMapper;
import com.elitel.frame.main.dao.ext.ExtBaseQuerysqlMapper;
import com.elitel.frame.main.dao.ext.ExtBaseTreeconfigMapper;
import com.elitel.frame.main.dao.ext.ExtCfgDbMapper;
import com.elitel.frame.main.dao.ext.ExtCfgExttreeMapper;
import com.elitel.frame.main.dao.ext.ExtSysExceptionMapper;
import com.elitel.frame.main.entity.ext.Census;
import com.elitel.frame.main.entity.ext.ExtBaseTreeconfig;
import com.elitel.frame.main.entity.ext.TreeConfig;
import com.elitel.frame.main.entity.ext.TreeConfig2;
import com.elitel.frame.main.entity.state.TimePushActivemq;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import com.elitel.frame.main.entity.vo.ServerStatistics;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.sf.json.JSONObject;

@Service
public class TreeConfigServiceImpl implements TreeConfigService {

    @Resource
    private ExtBaseTreeconfigMapper extBaseTreeconfigMapper;

    @Resource
    private ExtCfgExttreeMapper extCfgExttreeMapper;

    @Resource
    private CfgDbMapper cfgDbMapper;

    @Resource
    private ExtCfgDbMapper extCfgDbMapper;

    @Resource
    private CfgExttreeMapper cfgExttreeMapper;

    @Resource
    private CfgTableMapper cfgTableMapper;

//	@Resource
//	private RedisCacheService redisCacheService;

    @Resource
    private RedisCatchBasicServer redisCatchBasicServer;

    @Resource
    private CfgFieldMapper cfgFieldMapper;

    @Resource
    private ExtBaseQuerysqlMapper extBaseQuerysqlMapper;

    @Resource
    private ExtBaseQueryfieldMapper extBaseQueryfieldMapper;

    @Autowired
    private SysPrjserviceMapper sysPrjserviceMapper;

    @Autowired
    private RedisCacheProjectService redisCacheProjectService;

    @Autowired
    private DataBaseConnInfo dataBaseConnInfo;

    @Resource
    private RedisCacheTreeConfig redisCacheTreeConfig;

    @Resource
    private ExecuteSqlMapper executeSqlMapper;

    @Resource
    private ExtSysExceptionMapper extSysExceptionMapper;

//	@Autowired
//    private AmqpTemplate amqpTemplate;
//	@Autowired
//	private RabbitTemplate amqpTemplate;

    // 添加树节点
    @Override
    public String insertTreeNode(BaseTreeconfig baseTree) {
        String message = "fail";
        String type = dataBaseConnInfo.dataBaseType;
        int guid = 0;
        int ss = extBaseTreeconfigMapper.selectCount();
        if (ss > 0) {
            if ("mysql".equals(type) || type.equals("sqlite")) {
                guid = extBaseTreeconfigMapper.selectMaxGraMySql();
            } else if ("oracle".equals(type)) {
                guid = extBaseTreeconfigMapper.selectMaxGra();
            } else if (DataSourceType.POSTGRES.equals(type)) {
                guid = extBaseTreeconfigMapper.selectMaxGraPG();
            }
        }
        baseTree.setGuid(String.valueOf(guid + 2));
        int a = extBaseTreeconfigMapper.insertSelective(baseTree);
        if (a > 0) {
            message = "success";
        }
        return message;
    }

    @Override
    public String updateTreeNode(BaseTreeconfig baseTreeconfig) {
        String message = "feil";
        int a = extBaseTreeconfigMapper.updateByPrimaryKeySelective(baseTreeconfig);
        if (a > 0) {
            message = "success";
        }
        return message;
    }

    @Override
    public String insertTreeList(CfgExttree cfgTreeExt) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = simpleDateFormat.format(date);
        cfgTreeExt.setCreatedate(dateString);
        String message = "fail";
        int a = cfgExttreeMapper.insertSelective(cfgTreeExt);
        if (a > 0) {
            message = "success";
        }
        return message;
    }

    @Override
    public String deleteTreeList(String guid) {
        return null;
    }

    @Override
    public String updateTreeList(CfgExttree cfgTreeExt) {
        String message = "fail";
        int a = cfgExttreeMapper.updateByPrimaryKeySelective(cfgTreeExt);
        if (a > 0) {
            message = "success";
        }
        return message;
    }

    @Override
    public List<Census> getTreeList() {
        List<CfgDb> list = extCfgDbMapper.getAllListCfgDb();
        List<Census> censusList = new ArrayList<>();
        for (CfgDb c : list) {
            Census census = new Census();
            census.setPid("0");
            census.setId(c.getDbKey());
            census.setName(c.getDbMark() + "(" + c.getDbKey() + ")");
            List<CfgExttree> treeList = extCfgExttreeMapper.getTreeList(c.getDbKey());
            if (treeList.size() > 0) {
                List<Census> list2 = new ArrayList<>();
                for (CfgExttree cs : treeList) {
                    Census census2 = new Census();
                    census2.setId(cs.getGuid());
                    census2.setPid(cs.getDtDbKey());
                    census2.setName(cs.getServicename());
                    list2.add(census2);
                }
                census.setChildren(list2);
            }
            censusList.add(census);
        }
        return censusList;
    }

    // //获取
    // @Override
    // public List<BaseTreeconfig> selectTreeNode(String treeid, String sguid) {
    // String extend = extCfgExttreeMapper.selectTreeNode(treeid);
    // Map<String,Object> map = new HashMap<>();
    // map.put("treeid", treeid);
    // map.put("sguid", sguid);
    // List<BaseTreeconfig> list = null;
    // if (extend==null) {
    // list = extBaseTreeconfigMapper.selectTreeNode(map);
    // }else{
    //
    // }
    // return list;
    // }
    @Override
    public List<BaseTreeconfig> selectTreeNode(String treeid, String sguid) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public CfgExttree selectTreeFile(String guid) {
        CfgExttree cfgExttree = cfgExttreeMapper.selectByPrimaryKey(guid);
        return cfgExttree;
    }

    @Override
    public int selectCountGUID(String guid) {
        int count = extCfgExttreeMapper.selectCountGUID(guid);
        return count;
    }

    @Override
    public List<ExtBaseTreeconfig> selectTreeShow(String guid, String treeid) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("treeid", treeid);
        List<BaseTreeconfig> list = extBaseTreeconfigMapper.selectTreeShow(map);
        List<BaseTreeconfig> listing = new ArrayList<>();
        Map<Integer, BaseTreeconfig> map2 = new TreeMap<Integer, BaseTreeconfig>();
        for (BaseTreeconfig b : list) {
            map2.put(b.getGrade(), b);
        }
        for (Map.Entry<Integer, BaseTreeconfig> entry : map2.entrySet()) {
            listing.add(entry.getValue());
        }
        List<ExtBaseTreeconfig> list2 = new ArrayList<>();
        for (BaseTreeconfig baseTreeconfig : listing) {
            ExtBaseTreeconfig extBaseTreeconfig = new ExtBaseTreeconfig();
            extBaseTreeconfig.setGuid(Integer.valueOf(baseTreeconfig.getGuid()));
            extBaseTreeconfig.setParentguid(Integer.parseInt(baseTreeconfig.getParentguid()));
            String xx = cfgTableMapper.selectTableNamees(baseTreeconfig.getDtConfigId());
            // if (xx!=null) {
            // extBaseTreeconfig.setDtConfigId(xx);
            // }else {
            extBaseTreeconfig.setDtConfigId(baseTreeconfig.getDtConfigId());
            // }
            extBaseTreeconfig.setFieldKey(baseTreeconfig.getFieldKey());
            extBaseTreeconfig.setFieldPKey(baseTreeconfig.getFieldPKey());
            extBaseTreeconfig.setFieldShow(baseTreeconfig.getFieldShow());
            extBaseTreeconfig.setGrade(baseTreeconfig.getGrade());
            extBaseTreeconfig.setQueryCon(baseTreeconfig.getQueryCon());
            extBaseTreeconfig.setServiceid(baseTreeconfig.getServiceid());
            extBaseTreeconfig.setTreename(baseTreeconfig.getTreename());
            list2.add(extBaseTreeconfig);
        }
        return list2;
    }

    @Override
    public BaseTreeconfig selectOneTree(String guid) {
        BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectOneTree(guid);
        return baseTreeconfig;
    }

    @Override
    public String deleteTreeNode(String guid, String treeid, String seid) {
        String message = "fail";
        Map<String, Object> map = new HashMap<>();
        map.put("treeid", treeid);
        map.put("seid", seid);
        try {
            BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectOneTree(guid);
            int maxA = extBaseTreeconfigMapper.selectMaxGrade(map);
            int a = extBaseTreeconfigMapper.deleteByPrimaryKey(guid);
            map.put("grades", a);
            int count = extBaseQueryfieldMapper.deleteQueryfield(map);
            int countsize = extBaseQuerysqlMapper.deleteQuerysql(map);
            List<Integer> list = new ArrayList<>();
            if (maxA == baseTreeconfig.getGrade()) {
                list.add(maxA);
            } else {
                for (int s = baseTreeconfig.getGrade(); s <= maxA; s++) {
                    list.add(s);
                }
                for (Integer integer : list) {
                    map.put("grades", integer);
                    if (a > 0) {
                        int ss = extBaseTreeconfigMapper.deleteCengJi(map);
                        count += extBaseQueryfieldMapper.deleteQueryfield(map);
                        countsize += extBaseQuerysqlMapper.deleteQuerysql(map);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public CfgExttree getOneCfgExttree(String guid) {
        CfgExttree cfgExttree = extCfgExttreeMapper.selectByPrimaryKey(guid);
        return cfgExttree;
    }

    @Override
    public BaseTreeconfig selectTreeConfig(String guid, String grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("grade", grade);
        BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectTreeConfig(map);
        return baseTreeconfig;
    }

    @Override
    public CfgTable selectTableName(String dtConfigId) {
        CfgTable cfgTable = cfgTableMapper.selectBtConfigId(dtConfigId);
        return cfgTable;
    }

    @Override
    public CfgDb selectCfgDb(String dtDbKey) {
        CfgDb cfgDb = cfgDbMapper.selectByPrimaryKey(dtDbKey);
        return cfgDb;
    }

    @Override
    public List<BaseTreeconfig> selectTreeConfigList(String guid) {
        List<BaseTreeconfig> list = extBaseTreeconfigMapper.selectTreeConfigList(guid);
        return list;
    }

    @Override
    public PageResponseVo<BaseTreeconfig> selectTreeConfigAll(String serviceid) {
        List<BaseTreeconfig> list = extBaseTreeconfigMapper.selectTreeConfigAll(serviceid);
        int count = extBaseTreeconfigMapper.selectAllCount(serviceid);
        PageResponseVo<BaseTreeconfig> pageResponseVo = new PageResponseVo<>();
        pageResponseVo.setRows(list);
        pageResponseVo.setTotal(count);
        return pageResponseVo;
    }

    @Override
    public CfgField getAllListCfgField(String configid, String dbKey) {
        Map<String, Object> map = new HashMap<>();
        map.put("configid", configid);
        map.put("dtname", dbKey);
        CfgField cfgField = cfgFieldMapper.selectColumnOne(map);
        return cfgField;
    }

    @Override
    public List<CfgDb> selectCfgDbList() {
        List<CfgDb> list = cfgDbMapper.selectAllDb();
        return list;
    }

    @Override
    public List<CfgTable> selectCfgTableAll() {
        List<CfgTable> list = cfgTableMapper.selectAllTable();
        return list;
    }

    @Override
    public List<CfgExttree> setTreeing() {
        List<CfgExttree> list = extCfgExttreeMapper.selectAllTree();
        return list;
    }

    @Override
    public String selectTableCN(String dtConfigId) {
        String xx = cfgTableMapper.selectTableNamees(dtConfigId);
        return xx;
    }

    @Override
    public List<CfgExttree> getTreeListaLL() {
        List<CfgExttree> list = extCfgExttreeMapper.selectAllTree();
        return list;
    }

    @Override
    public String deleteTreeConfig(String guid) {
        String message = "fail";
        int a = extCfgExttreeMapper.deleteByPrimaryKey(guid);
        if (a > 0) {
            extBaseQueryfieldMapper.deleteQueryfieldByServiceId(guid);
            extBaseQuerysqlMapper.deleteQuerysqlByServiceId(guid);
            message = "success";
        }
        return message;
    }

    @Override
    public Map<String, Object> selectColumnMap(String dbid) {
        List<CfgField> list = cfgFieldMapper.selectColumnList(dbid);
        Map<String, Object> map = new HashMap<>();
        for (CfgField c : list) {
            map.put(c.getDfName(), c.getDfNameCn());
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> executequerySql(String sqlString) {
        List<Map<String, Object>> list = extCfgExttreeMapper.executequerySql(sqlString);
        return list;
    }

    @Override
    public BaseTreeconfig selectTreeConfigOne(String guid, String grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("grade", grade);
        BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectTreeConfigOne(map);
        return baseTreeconfig;
    }

    @Override
    public BaseQuerysql selectConQuery(String serviceID, String grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("serviceID", serviceID);
        map.put("grade", grade);
        BaseQuerysql baseQuerysql = extBaseQuerysqlMapper.selectByServerId(map);
        return baseQuerysql;
    }

    @Override
    public String getDBType(String serviceID) {
        CfgExttree cfgExttree = cfgExttreeMapper.selectByPrimaryKey(serviceID);
        CfgDb cfgDb = extCfgDbMapper.selectByPrimaryDBSign(cfgExttree.getDtDbKey());
        return cfgDb.getDbVersion();
    }

    @Override
    public List<BaseQueryfield> selectTreeColumn(String guid) {
        List<BaseQueryfield> list = extBaseQueryfieldMapper.selectQueryFiled(guid);
        return list;
    }

    @Override
    public void deletetreeconfigServerByPrjservice(SysPrjservice prjservice) {
        // 删除服务中间表信息
        sysPrjserviceMapper.deleteByPrimaryKey(prjservice.getGuid());
        if (extCfgExttreeMapper.selectByPrimaryKey(prjservice.getServicecode()) != null) {
            extCfgExttreeMapper.deleteByPrimaryKey(prjservice.getServicecode());
        }
        extBaseQueryfieldMapper.deleteQueryfieldByServiceId(prjservice.getServicecode());
        if (extBaseQuerysqlMapper.selectByServiceId(prjservice.getServicecode()) > 1) {
            extBaseQuerysqlMapper.deleteQuerysqlByServiceId(prjservice.getServicecode());
        }
        extBaseTreeconfigMapper.deleteByServiceId(prjservice.getServicecode());
        // 刷新工程服务树
        redisCacheProjectService.freshProjectServerTree();
    }

    public BaseQuerysql selectQuerySql(String guid, int grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("grade", grade);
        BaseQuerysql baseQuerysql = extBaseQuerysqlMapper.selectQuerySql(map);
        // BaseQuerysql baseQuerysql = null;
        return baseQuerysql;
    }

    /**
     * <pre>
     * processSqlByFreemarker(freemarker处理sql)
     * &#64;author：FanWenquan
     * &#64;date：2017年8月31日 上午10:34:17
     * &#64;param sql
     * &#64;param root
     * &#64;return
     * </pre>
     */
    private String processSqlByFreemarker(String sql, Map root) {
        String str = "";
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate", sql);
        cfg.setTemplateLoader(stringLoader);
        try {
            Template template = cfg.getTemplate("myTemplate", "utf-8");
            StringWriter writer = new StringWriter();
            template.process(root, writer);
            str = writer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return str;
    }

    public List<TreeConfig> recursiveTree(CfgDb cfgDb, String pid, List<BaseTreeconfig> btcList, int grade,
                                          String tableName, String querycon, List<String> sqlList) {
        TreeConfig node = new TreeConfig();
        BaseTreeconfig baseTree = null;
        for (BaseTreeconfig baseTreeconfig : btcList) {
            if (grade == baseTreeconfig.getGrade()) {
                baseTree = baseTreeconfig;
                break;
            }
        }
        if (baseTree == null) {
            return null;
        }
        CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTree.getDtConfigId());
        String sql = "SELECT " + baseTree.getFieldKey() + " " + "AS ID," + " " + baseTree.getFieldShow() + " "
                + "AS NAME," + "'" + pid + "'" + "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE  "
                + baseTree.getFieldPKey() + " = '" + pid + "'" + querycon;
        sqlList.add(sql);
        List<Map<String, Object>> lists = executequerySql(cfgDb, sql);
        List<TreeConfig> list = new ArrayList<>();
        for (Map<String, Object> map : lists) {
            TreeConfig treeConfig = new TreeConfig();
            treeConfig.setId((String) map.get("ID"));
            treeConfig.setName((String) map.get("NAME"));
            treeConfig.setPid(pid);
            treeConfig.setGrade(grade);
            list.add(treeConfig);
        }
        for (TreeConfig treeConfig : list) {
            List<TreeConfig> n = recursiveTree(cfgDb, treeConfig.getId(), btcList, grade + 1, tableName, querycon, sqlList); // 递归
            treeConfig.setChildren(n);
        }
        return list;
    }

    public List<Map<String, Object>> executequerySql(CfgDb cfgDb, String sqlString) {
        List<Map<String, Object>> list = executeSqlMapper.executequerySql(sqlString);
        return list;
    }

    @Override
    public Object selectTreeConfigFile(CfgDb cfgDb, String guid, String conquery) {
        Map mapsts = new HashMap();
        Object object = new Object();
        long serverStartTime = System.currentTimeMillis();
        if (conquery != null && !"".equals(conquery)) {
            JSONObject jasonObject = JSONObject.fromObject(conquery);
            mapsts = (Map) jasonObject;
        }
        String sqls = "";
        List<String> sqlList = new ArrayList<>();
        CfgExttree cfgExttree = extCfgExttreeMapper.selectByPrimaryKey(guid);
        List<TreeConfig> list = new ArrayList<>();
        try {

            if (Integer.parseInt(String.valueOf(cfgExttree.getIslazyload())) == 1) {
                BaseQuerysql baseQuerysql = selectQuerySql(guid, 1);
                String sqlconquery = "";
                if (baseQuerysql != null) {
                    sqlconquery = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapsts);
                }
                if (cfgExttree.getIsusetop() == 0) {
                    System.out.println("慢加载xx不用顶级节点");
                    BaseTreeconfig baseTreeconfig = redisCacheTreeConfig.getBaseTreeCacheOne(guid, 1);
                    CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());
                    // sqlString = "SELECT "+baseTreeconfig.getFieldKey()+"
                    // "+"AS ID,"+" "+baseTreeconfig.getFieldShow()+" "+"AS
                    // NAME,"+" "+0+" "+"AS PID FROM "+cfgTable.getDtName();
                    // sqlString = "SELECT "+baseTreeconfig.getFieldKey()+"
                    // "+"AS ID,"+" "+baseTreeconfig.getFieldShow()+" "+"AS
                    // NAME,"+" "+0+" "+"AS PID FROM "+cfgTable.getDtName()+"
                    // "+"WHERE 1=1"+" "+baseTreeconfig.getQueryCon();
                    String sqlString = "SELECT * FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + " " + sqlconquery;
                    List<Map<String, Object>> list2 = executequerySql(cfgDb, sqlString);
                    List<Map<String, Object>> list3 = new ArrayList<>();
                    for (Map<String, Object> m : list2) {
                        Map<String, Object> map = new HashMap<>();
                        System.out.println(m.toString());
                        Map<String, Object> map6 = new HashMap<>();
                        for (Map.Entry<String, Object> entry : m.entrySet()) {
                            if (entry.getValue() != null) {
                                System.out.println(entry.toString());
                                if (baseTreeconfig.getFieldKey().equals(entry.getKey())) {
                                    map.put("id", entry.getValue());
                                }
                                if (baseTreeconfig.getFieldShow().equals(entry.getKey())) {
                                    map.put("name", entry.getValue());
                                }
                            }
                        }

                        // for(Map.Entry<String, Object> entry:map6.entrySet()){
                        // map.put(entry.getKey(), entry.getValue());
                        // }
                        map.put("pid", "1");
                        map.put("otherfield", m);
                        list3.add(map);
                    }
                    object = list3;
                } else {
                    System.out.println("慢加载用顶级节点");
                    List<TreeConfig> configs = new ArrayList<>();
                    TreeConfig2 treeCon = new TreeConfig2();
                    treeCon.setId("1");
                    treeCon.setName(cfgExttree.getTopnode());
                    treeCon.setPid("0");
                    // list.add(treeCon);
                    BaseTreeconfig baseTreeconfig = redisCacheTreeConfig.getBaseTreeCacheOne(guid, 1);
                    CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());
                    String sqlString = "SELECT * FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + " " + sqlconquery;
                    List<Map<String, Object>> list2 = executeSqlMapper.executequerySql(sqlString);
                    List<Map<String, Object>> list3 = new ArrayList<>();
                    for (Map<String, Object> m : list2) {
                        Map<String, Object> map = new HashMap<>();
                        for (Map.Entry<String, Object> entry : m.entrySet()) {
                            if (baseTreeconfig.getFieldKey().equals(entry.getKey())) {
                                map.put("id", entry.getValue());
                            }
                            if (baseTreeconfig.getFieldShow().equals(entry.getKey())) {
                                map.put("name", entry.getValue());
                            }
                            map.put("otherfield", m);
                        }
                        map.put("pid", "1");
                        list3.add(map);
                    }
                    treeCon.setChildren(list3);
                    object = treeCon;
                }
            } else {
                if (cfgExttree.getIsusetop() == 0) {

                    System.out.println("全加载不用顶级节点");
                    TreeConfig treeCon = new TreeConfig();
                    treeCon.setId("1");
                    treeCon.setName(cfgExttree.getTopnode());
                    treeCon.setPid("0");
                    list.add(treeCon);
                    List<BaseTreeconfig> baseTreeconfigLists = redisCacheTreeConfig.getBaseTreeCache(guid);
                    TreeMap<Integer, BaseTreeconfig> treeMaping = new TreeMap<Integer, BaseTreeconfig>();
                    for (BaseTreeconfig bs : baseTreeconfigLists) {
                        treeMaping.put(bs.getGrade(), bs);
                    }
                    List<BaseTreeconfig> baseTreeconfigList = new ArrayList<>();
                    for (Map.Entry<Integer, BaseTreeconfig> entry : treeMaping.entrySet()) {
                        baseTreeconfigList.add(entry.getValue());
                    }
                    Map<String, Object> map = new HashMap<>();
                    List<TreeConfig> tList = new ArrayList<>();
                    String sql = "";
                    int a = 1;
                    Map<String, List<TreeConfig>> conMap = new HashMap<>();
                    List<TreeConfig> lConfigs = new ArrayList<>();
                    for (BaseTreeconfig b : baseTreeconfigList) {
                        CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(b.getDtConfigId());
                        if (b.getGrade() == 1) {
                            BaseQuerysql baseQuerysql = selectQuerySql(guid, 1);
                            String sqlconquerys = "";
                            if (baseQuerysql != null) {
                                sqlconquerys = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapsts);
                            }
                            sql = "SELECT " + b.getFieldKey() + " " + "AS ID," + " " + b.getFieldShow() + " "
                                    + "AS NAME," + " " + 0 + " " + "AS PID FROM " + cfgTable.getDtName() + " "
                                    + "WHERE 1=1" + sqlconquerys;
                            List<Map<String, Object>> lists = executequerySql(cfgDb, sql);
                            List<String> conList = new ArrayList<>();
                            for (Map<String, Object> mp : lists) {
                                TreeConfig treeConfig = new TreeConfig();
                                conList.add((String) mp.get("ID"));
                                treeConfig.setId((String) mp.get("ID"));
                                treeConfig.setName((String) mp.get("NAME"));
                                treeConfig.setPid("1");
                                treeConfig.setGrade(1);
                                tList.add(treeConfig);
                                lConfigs.add(treeConfig);
                            }
                            int grade = 2;
                            if (lConfigs.size() > 0) {
                                for (TreeConfig treeConfig : lConfigs) {
                                    BaseQuerysql baseQuerysqles = selectQuerySql(guid, grade);
                                    if (baseQuerysqles != null) {
                                        sqlconquerys = processSqlByFreemarker(baseQuerysqles.getSqlcontent(), mapsts);
                                    }
                                    List<TreeConfig> n = recursiveTree(cfgDb, treeConfig.getId(), baseTreeconfigLists,
                                            grade, cfgTable.getDtName(), sqlconquerys, sqlList); // 递归
                                    treeConfig.setChildren(n);
                                    // grade++;
                                }
                            }
                        }
                    }
                    treeCon.setChildren(lConfigs);
                    object = lConfigs;

                } else {
                    System.out.println("全加载用顶级节点");
                    TreeConfig treeCon = new TreeConfig();
                    treeCon.setId("1");
                    treeCon.setName(cfgExttree.getTopnode());
                    treeCon.setPid("0");
                    list.add(treeCon);
                    List<BaseTreeconfig> baseTreeconfigLists = redisCacheTreeConfig.getBaseTreeCache(guid);
                    TreeMap<Integer, BaseTreeconfig> treeMaping = new TreeMap<Integer, BaseTreeconfig>();
                    for (BaseTreeconfig bs : baseTreeconfigLists) {
                        treeMaping.put(bs.getGrade(), bs);
                    }
                    List<BaseTreeconfig> baseTreeconfigList = new ArrayList<>();
                    for (Map.Entry<Integer, BaseTreeconfig> entry : treeMaping.entrySet()) {
                        baseTreeconfigList.add(entry.getValue());
                    }
                    Map<String, Object> map = new HashMap<>();
                    List<TreeConfig> tList = new ArrayList<>();
                    String sql = "";
                    int a = 1;
                    Map<String, List<TreeConfig>> conMap = new HashMap<>();
                    List<TreeConfig> lConfigs = new ArrayList<>();
                    for (BaseTreeconfig b : baseTreeconfigList) {
                        CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(b.getDtConfigId());
                        if (b.getGrade() == 1) {
                            BaseQuerysql baseQuerysql = selectQuerySql(guid, 1);
                            String sqlconquerys = "";
                            if (baseQuerysql != null) {
                                sqlconquerys = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapsts);
                            }
                            sql = "SELECT " + b.getFieldKey() + " " + "AS ID," + " " + b.getFieldShow() + " "
                                    + "AS NAME," + " " + 0 + " " + "AS PID FROM " + cfgTable.getDtName() + " "
                                    + "WHERE 1=1" + sqlconquerys;
                            List<Map<String, Object>> lists = executequerySql(cfgDb, sql);
                            List<String> conList = new ArrayList<>();
                            for (Map<String, Object> mp : lists) {
                                TreeConfig treeConfig = new TreeConfig();
                                conList.add((String) mp.get("ID"));
                                treeConfig.setId((String) mp.get("ID"));
                                treeConfig.setName((String) mp.get("NAME"));
                                treeConfig.setPid("1");
                                treeConfig.setGrade(1);
                                tList.add(treeConfig);
                                lConfigs.add(treeConfig);
                            }
                            int grade = 2;
                            if (lConfigs.size() > 0) {
                                for (TreeConfig treeConfig : lConfigs) {
                                    BaseQuerysql baseQuerysqles = selectQuerySql(guid, grade);
                                    if (baseQuerysqles != null) {
                                        sqlconquerys = processSqlByFreemarker(baseQuerysqles.getSqlcontent(), mapsts);
                                    }
                                    List<TreeConfig> n = recursiveTree(cfgDb, treeConfig.getId(), baseTreeconfigLists,
                                            grade, cfgTable.getDtName(), sqlconquerys, sqlList); // 递归
                                    treeConfig.setChildren(n);
                                    // grade++;
                                }
                            }
                        }
                    }
                    treeCon.setChildren(lConfigs);
                    object = treeCon;
                }
            }
//			final String sessionID = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
//					.getRequest().getSession().getId();
//			long serverEndTime = System.currentTimeMillis();
//			long serverInterval = serverEndTime - serverStartTime;
//			long sqlInterval = 0;
//			if (TimePushActivemq.getPushSwitch() == 0 && (serverInterval >= TimePushActivemq.getTimeInterval()
//					|| sqlInterval >= TimePushActivemq.getTimeInterval())) {
//				final ServerStatistics server = new ServerStatistics();
//				server.setServerName(guid);
//				server.setSql(JSON.toJSONString(sqlList));
//				server.setServerTime(serverInterval);
//				server.setSqlTime(sqlInterval);
//				amqpTemplate.convertAndSend("serverTimeDestination", JSON.toJSONString(server));
//				jmsTemplate.send(destination, new MessageCreator() {
//
//					@Override
//					public Message createMessage(Session session) throws JMSException {
//						FileWriterUtil.saveAsFileWriter(sessionID, JSONObject.fromObject(server).toString());
//						return session.createTextMessage(JSON.toJSONString(server));
//					}
//				});
//			}
        } catch (Exception e) {
            throw new BaseException(e, getSysException());
        }
        return object;
    }

    public Map<String, Object> getAllGradeSelect(String ServiceId, Map mapsts) {
        List<BaseTreeconfig> list = redisCacheTreeConfig.getBaseTreeCache(ServiceId);
        CfgExttree cfgExttree = getOneCfgExttree(ServiceId);
        CfgDb cfgDb = redisCacheTreeConfig.selectCfgDbOne(cfgExttree.getDtDbKey());
        Map<String, Object> map = new HashMap<>();
        List<List<Map<String, Object>>> lists = new ArrayList<>();
        for (BaseTreeconfig baseTreeconfig : list) {
            if (baseTreeconfig.getGrade() == 1) {
                BaseQuerysql baseQuerysql = selectQuerySql(ServiceId, baseTreeconfig.getGrade());
                String sqlconquery = "";
                if (baseQuerysql != null) {
                    sqlconquery = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapsts);
                }
                CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());
                String sql = "";
                if (!"".equals(sqlconquery)) {
                    sql = "SELECT " + baseTreeconfig.getFieldKey() + " " + "AS ID," + " "
                            + baseTreeconfig.getFieldShow() + " " + "AS NAME," + " " + baseTreeconfig.getFieldPKey()
                            + " " + "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE 1=1 " + sqlconquery;
                }
                String sqles = "SELECT " + baseTreeconfig.getFieldKey() + " " + "AS ID," + " "
                        + baseTreeconfig.getFieldShow() + " " + "AS NAME," + " " + baseTreeconfig.getFieldPKey() + " "
                        + "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE 1=1 ";
                List<Map<String, Object>> list2 = null;
                if (!"".equals(sql)) {
                    list2 = executequerySql(cfgDb, sql);
                }
                if (list2 != null) {
                    lists.add(list2);
                }
                list2 = executequerySql(cfgDb, sqles);
                List<TreeConfig> listes = new ArrayList<>();
                for (Map<String, Object> mapes : list2) {
                    TreeConfig treeConfig = new TreeConfig();
                    treeConfig.setId((String) mapes.get("ID"));
                    treeConfig.setName((String) mapes.get("NAME"));
                    treeConfig.setPid("0");
                    treeConfig.setGrade(1);
                    listes.add(treeConfig);
                }
                int grade = 1;
                List<List<Map<String, Object>>> listess = new ArrayList<>();
                for (TreeConfig treeConfig : listes) {
                    recursiveTreees(cfgDb, map, listess, ServiceId, treeConfig.getId(), list, grade + 1, mapsts); // 递归
                    // treeConfig.setChildren(n);
                }
                if (listess.size() > 0) {
                    map.put("2", listess);
                }
            }
        }
        if (lists.size() > 0) {
            map.put(String.valueOf(1), lists);
        }
        return map;
    }

    public Object recursiveTreees(CfgDb cfgDb, Map<String, Object> mapes, List<List<Map<String, Object>>> listess,
                                  String serviceID, String pid, List<BaseTreeconfig> btcList, int grade, Map mapsts) {
        BaseQuerysql baseQuerysqls = selectQuerySql(serviceID, grade);
        String sqlconquery = "";
        if (baseQuerysqls != null) {
            sqlconquery = processSqlByFreemarker(baseQuerysqls.getSqlcontent(), mapsts);
        }
        BaseTreeconfig baseTree = null;
        for (BaseTreeconfig baseTreeconfig : btcList) {
            if (grade == baseTreeconfig.getGrade()) {
                baseTree = baseTreeconfig;
                break;
            }
        }
        if (baseTree == null) {
            return null;
        }
        CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTree.getDtConfigId());
        String sql = "";
        if (!"".equals(sqlconquery)) {
            sql = "SELECT " + baseTree.getFieldKey() + " " + "AS ID," + " " + baseTree.getFieldShow() + " " + "AS NAME,"
                    + "'" + pid + "'" + "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE  "
                    + baseTree.getFieldPKey() + " = '" + pid + "'" + sqlconquery;
        }
        String sqles = "SELECT " + baseTree.getFieldKey() + " " + "AS ID," + " " + baseTree.getFieldShow() + " "
                + "AS NAME," + "'" + pid + "'" + "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE  "
                + baseTree.getFieldPKey() + " = '" + pid + "'";
        List<Map<String, Object>> lists = null;
        int a = 0;
        if (!"".equals(sql)) {
            lists = executequerySql(cfgDb, sql);
            a = lists.size();
        }
        List<Map<String, Object>> listes = executequerySql(cfgDb, sqles);
        List<TreeConfig> list = new ArrayList<>();
        if (lists != null && a > 0) {
            listess.add(lists);
            // map.put(String.valueOf(grade),lists);
        }
        List<TreeConfig> listing = new ArrayList<>();
        for (Map<String, Object> map : listes) {
            TreeConfig treeConfig = new TreeConfig();
            treeConfig.setId((String) map.get("ID"));
            treeConfig.setName((String) map.get("NAME"));
            treeConfig.setPid(pid);
            treeConfig.setGrade(grade);
            listing.add(treeConfig);
        }
        List<List<Map<String, Object>>> listesing = new ArrayList<>();
        for (TreeConfig treeConfig : listing) {
            recursiveTreees(cfgDb, mapes, listesing, treeConfig.getId(), serviceID, btcList, grade + 1, mapsts); // 递归
            // treeConfig.setChildren(n);
            System.out.println("第几次来");
        }
        if (listesing.size() > 0) {
            mapes.put(String.valueOf(grade), listesing);
        }

        // }
        return mapes;
    }

    // 符合条件
    private List<TreeConfig> getSelectMap(String serviceID, Map<String, Object> map) {
        List<TreeConfig> list1 = new ArrayList<>();
        List<TreeConfig> list2 = new ArrayList<>();
        List<TreeConfig> list3 = new ArrayList<>();
        List<TreeConfig> list4 = new ArrayList<>();
        List<TreeConfig> list5 = new ArrayList<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            int count = entry.getValue().toString().length();
            String xx = entry.getValue().toString().substring(2, count - 2);
            String[] b = xx.split("},");
            List<String> listing = new ArrayList<>();
            int a = 1;
            for (String x : b) {
                if (a != b.length) {
                    x += "}";
                }
                listing.add(x);
            }
            int aee = 0;
            for (String maps : listing) {
                Map<String, Object> map2 = new HashMap<>();
                maps = maps.substring(1, maps.length() - 1);
                String[] strs = maps.split(",");
                int ass = 0;
                if (aee == 0) {
                    for (String x : strs) {
                        map2.put(x.split("=")[0], x.split("=")[1]);
                    }
                } else {
                    for (String x : strs) {
                        if (ass == 0) {
                            x = x.substring(1, x.length());
                        }
                        ass++;
                        map2.put(x.split("=")[0], x.split("=")[1]);
                    }
                }
                aee++;
                TreeConfig treeConfig = new TreeConfig();
                treeConfig.setId(String.valueOf(map2.get("ID")));
                treeConfig.setPid("0");
                treeConfig.setName(String.valueOf(map2.get("NAME")));
                treeConfig.setGrade(1);
                list1.add(treeConfig);
            }
        }
        return list1;
    }

    private List<TreeConfig> getSelectMaping(List<String> sqlList, CfgDb cfgdb, String serviceID, Map<String, Object> map) {
        List<TreeConfig> list1 = new ArrayList<>();
        List<TreeConfig> list2 = new ArrayList<>();
        List<TreeConfig> list3 = new ArrayList<>();
        List<TreeConfig> list4 = new ArrayList<>();
        List<TreeConfig> list5 = new ArrayList<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (Integer.valueOf(entry.getKey()) == 1) {
                int count = entry.getValue().toString().length();
                String xx = entry.getValue().toString().substring(2, count - 2);
                String[] b = xx.split("},");
                List<String> listing = new ArrayList<>();
                int a = 1;
                for (String x : b) {
                    if (a != b.length) {
                        x += "}";
                    }
                    listing.add(x);
                }
                int aee = 0;
                for (String maps : listing) {
                    Map<String, Object> map2 = new HashMap<>();
                    maps = maps.substring(1, maps.length() - 1);
                    String[] strs = maps.split(",");
                    int ass = 0;
                    if (aee == 0) {
                        for (String x : strs) {
                            map2.put(x.split("=")[0].trim(), x.split("=")[1]);
                        }
                    } else {
                        for (String x : strs) {
                            if (ass == 0) {
                                x = x.substring(1, x.length());
                            }
                            ass++;
                            map2.put(x.split("=")[0].trim(), x.split("=")[1]);
                        }
                    }
                    aee++;
                    TreeConfig treeConfig = new TreeConfig();
                    treeConfig.setId(String.valueOf(map2.get("ID")));
                    treeConfig.setPid("0");
                    treeConfig.setName(String.valueOf(map2.get("NAME")));
                    treeConfig.setGrade(1);
                    list1.add(treeConfig);
                }
            } else {
                int count = entry.getValue().toString().length();
                String xx = entry.getValue().toString().substring(2, count - 2);
                String[] b = xx.split("},");
                List<String> listing = new ArrayList<>();
                int a = 1;
                for (String x : b) {
                    if (a != b.length) {
                        x += "}";
                    }
                    listing.add(x);
                }
                int aee = 0;
                int ary = 0;
                for (String maps : listing) {
                    if (ary == 0) {
                        Map<String, Object> map2 = new HashMap<>();
                        maps = maps.substring(1, maps.length() - 1);
                        String[] strs = maps.split(",");
                        int ass = 0;
                        if (aee == 0) {
                            for (String x : strs) {
                                map2.put(x.split("=")[0], x.split("=")[1]);
                            }
                        } else {
                            for (String x : strs) {
                                if (ass == 0) {
                                    x = x.substring(1, x.length());
                                }
                                ass++;
                                map2.put(x.split("=")[0], x.split("=")[1]);
                            }
                        }
                        aee++;
                        TreeConfig treeConfig = getselectOneTreeone(cfgdb, serviceID, Integer.valueOf(entry.getKey()),
                                map2);
                        if (Integer.valueOf(entry.getKey()) == 2) {
                            list2.add(treeConfig);
                        }
                        if (Integer.valueOf(entry.getKey()) == 3) {
                            list3.add(treeConfig);
                        }
                        if (Integer.valueOf(entry.getKey()) == 4) {
                            list4.add(treeConfig);
                        }
                        if (Integer.valueOf(entry.getKey()) == 5) {
                            list5.add(treeConfig);
                        }
                    }
                }
                ary++;
            }
        }
        List<TreeConfig> list = new ArrayList<>();
        if (list1.size() > 0) {
            for (TreeConfig treeConfig : list1) {
                list.add(treeConfig);
            }
        }
        if (list2.size() > 0) {
            for (TreeConfig treeConfig : list2) {
                list.add(treeConfig);
            }
        }
        if (list3.size() > 0) {
            for (TreeConfig treeConfig : list3) {
                list.add(treeConfig);
            }
        }
        if (list4.size() > 0) {
            for (TreeConfig treeConfig : list4) {
                list.add(treeConfig);
            }
        }
        if (list1.size() > 0) {
            for (TreeConfig treeConfig : list5) {
                list.add(treeConfig);
            }
        }

        return list;
    }

    private TreeConfig getselectOneTreeone(CfgDb cfgDb, String guid, Integer valueOf, Map<String, Object> map2) {
        TreeConfig treeConfig = new TreeConfig();
        for (Map.Entry<String, Object> entry : map2.entrySet()) {
            System.out.println(entry.getKey());
            if ("ID".equals(entry.getKey().trim())) {
                treeConfig.setId(String.valueOf(entry.getValue()));
            }
            if ("NAME".equals(entry.getKey().trim())) {
                treeConfig.setName(String.valueOf(entry.getValue()));
            }
            if ("PID".equals(entry.getKey().trim())) {
                treeConfig.setPid(String.valueOf(entry.getValue()));
            }
        }
        List<BaseTreeconfig> list = selectTreeConfigList(guid);
        Map<Integer, BaseTreeconfig> baseTreeMap = new HashMap<>();
        for (BaseTreeconfig baseTreeconfig : list) {
            baseTreeMap.put(baseTreeconfig.getGrade(), baseTreeconfig);
        }
        for (int i = valueOf - 1; i > 0; i--) {
            BaseTreeconfig baseTreeconfig = baseTreeMap.get(i);
            CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());
            String sql = "SELECT " + baseTreeconfig.getFieldKey() + " " + "AS ID," + " " + baseTreeconfig.getFieldShow()
                    + " " + "AS NAME," + " " + baseTreeconfig.getFieldPKey() + " " + "AS PID FROM "
                    + cfgTable.getDtName() + " " + "WHERE  " + baseTreeconfig.getFieldKey() + " = '"
                    + treeConfig.getPid() + "'";
            List<Map<String, Object>> lists = executequerySql(cfgDb, sql);
            int a = 0;
            for (Map<String, Object> m : lists) {
                if (a == 0) {
                    List<TreeConfig> list2 = new ArrayList<>();
                    list2.add(treeConfig);
                    for (Map.Entry<String, Object> entry : m.entrySet()) {
                        treeConfig.setChildren(list2);
                        if ("ID".equals(entry.getKey())) {
                            treeConfig.setId(String.valueOf(entry.getValue()));
                        }
                        if ("NAME".equals(entry.getKey())) {
                            treeConfig.setName(String.valueOf(entry.getValue()));
                        }
                        if (i == 1) {
                            if ("PID".equals(entry.getKey())) {
                                treeConfig.setPid(String.valueOf(0));
                            }
                        } else {
                            if ("PID".equals(entry.getKey())) {
                                treeConfig.setPid(String.valueOf(entry.getValue()));
                            }
                        }
                    }
                }
                a++;
            }
        }
        return treeConfig;
    }

    public Object getOneGrade(List<String> sqlList, String ServiceId) {
        String guid = ServiceId;
        CfgExttree cfgExttree = getOneCfgExttree(guid);
        CfgDb cfgDb = redisCacheTreeConfig.selectCfgDbOne(cfgExttree.getDtDbKey());
        List<BaseTreeconfig> baseTreeconfigLists = redisCacheTreeConfig.getBaseTreeCache(ServiceId);
        BaseTreeconfig baseTreeconfigs = null;
        String sql = "";
        int as = 2;
        for (BaseTreeconfig b : baseTreeconfigLists) {
            if (b.getGrade() == as) {
                baseTreeconfigs = b;
            }
        }
        List<TreeConfig2> lists = new ArrayList<>();
        List<TreeConfig> list = new ArrayList<>();
        if (cfgExttree.getIsusetop() == 0) {
            System.out.println("慢加载不用顶级节点");
            BaseTreeconfig baseTreeconfig = redisCacheTreeConfig.getBaseTreeCacheOne(guid, 1);
            if (baseTreeconfig == null) {
                return new Object();
            }
            CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());
            Map<String, Object> mapes = new HashMap<>();
            BaseQuerysql baseQuerysql = selectQuerySql(ServiceId, baseTreeconfig.getGrade());
            String sqlconquery = "";
            if (baseQuerysql != null) {
                sqlconquery = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapes);
            }
            String sqlString = "SELECT * FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + " " + sqlconquery;
            sqlList.add(sqlString);
//			String sqlStrings = "SELECT " + baseTreeconfig.getFieldKey() + " " + "AS ID," + " "
//					+ baseTreeconfig.getFieldShow() + " " + "AS NAME," + " " + baseTreeconfig.getFieldPKey() + " "
//					+ "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + " " + sqlconquery;
            List<Map<String, Object>> list2 = executequerySql(cfgDb, sqlString);
            List<Map<String, Object>> list3 = new ArrayList<>();
            for (Map<String, Object> m : list2) {
                Map<String, Object> map = new HashMap<>();
                for (Map.Entry<String, Object> entry : m.entrySet()) {
                    if (entry.getValue() != null) {
                        System.out.println(entry.toString());
                        if (baseTreeconfig.getFieldKey().equals(entry.getKey())) {
                            map.put("id", entry.getValue());
                        }
                        if (baseTreeconfig.getFieldShow().equals(entry.getKey())) {
                            map.put("name", entry.getValue());
                        }
                    }
                }
                if (baseTreeconfigs == null) {
                    map.put("isParent", false);
                } else {
                    map.put("isParent", true);
                }
                map.put("pid", "1");
                map.put("grade", 1);
                map.put("otherfield", m);
                list3.add(map);
            }
            return list3;
        } else {
            System.out.println("慢加载用顶级节点");
            List<TreeConfig> configs = new ArrayList<>();
            TreeConfig2 treeCon = new TreeConfig2();
            treeCon.setId("1");
            treeCon.setName(cfgExttree.getTopnode());
            treeCon.setPid("0");
            lists.add(treeCon);
            BaseTreeconfig baseTreeconfig = redisCacheTreeConfig.getBaseTreeCacheOne(guid, 1);
            Map<String, Object> mapes = new HashMap<>();
            CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());
            BaseQuerysql baseQuerysql = selectQuerySql(ServiceId, baseTreeconfig.getGrade());
            String sqlconquery = "";
            if (baseQuerysql != null && !"".equals(baseQuerysql.getSqlcontent())
                    && baseQuerysql.getSqlcontent() != null) {
                sqlconquery = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapes);
            }
            String sqlString = "SELECT * FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + " " + sqlconquery;
            sqlList.add(sqlString);
            // String sqlString = "SELECT "+baseTreeconfig.getFieldKey()+" "+"AS
            // ID,"+" "+baseTreeconfig.getFieldShow()+" "+"AS NAME,"+"
            // "+baseTreeconfig.getFieldPKey()+" "+"AS PID FROM
            // "+cfgTable.getDtName()+" "+"WHERE 1=1"+" "+sqlconquery;
            List<Map<String, Object>> list2 = executequerySql(cfgDb, sqlString);
            List<Map<String, Object>> list3 = new ArrayList<>();
            for (Map<String, Object> m : list2) {
                Map<String, Object> map = new HashMap<>();
                for (Map.Entry<String, Object> entry : m.entrySet()) {
                    if (entry.getValue() != null) {
                        System.out.println(entry.toString());
                        if (baseTreeconfig.getFieldKey().equals(entry.getKey())) {
                            map.put("id", entry.getValue());
                        }
                        if (baseTreeconfig.getFieldShow().equals(entry.getKey())) {
                            map.put("name", entry.getValue());
                        }
                    }
                }
                if (baseTreeconfigs == null) {
                    map.put("isParent", false);
                } else {
                    map.put("isParent", true);
                }
                map.put("pid", "1");
                map.put("grade", 1);
                map.put("otherfield", m);
                list3.add(map);
            }
            treeCon.setChildren(list3);
            return treeCon;
        }
    }

    @Override
    public Object getPartTreeConfig(CfgDb cfgDb, String id, String serviceID, String grade, String conquery) {
        Map mapsts = new HashMap();
        Object object = new Object();
        long serverStartTime = System.currentTimeMillis();
        List<String> sqlList = new ArrayList<>();
        if (conquery != null && !"".equals(conquery)) {
            JSONObject jasonObject = JSONObject.fromObject(conquery);
            mapsts = (Map) jasonObject;
        }
        // BaseQuerysql xx =
        // treeConfigServiceImpl.selectConQuery(serviceID,grade);
        try {
            if (grade == null && id == null && mapsts.size() == 0) {
                object = getOneGrade(sqlList, serviceID);
            } else if (grade == null && id == null && mapsts.size() > 0) {
                Map<String, Object> mapes = getAllGradeSelect(serviceID, mapsts);
                Map<String, Object> treeMap = new TreeMap<>();
                for (Map.Entry<String, Object> entry : mapes.entrySet()) {
                    treeMap.put(entry.getKey(), entry.getValue());
                }
                List<TreeConfig> list = getSelectMaping(sqlList, cfgDb, serviceID, treeMap);
                List<TreeConfig> list2 = new ArrayList<>();
                int a = 0;
                for (TreeConfig t : list) {
                    if (a != list.size() - 2) {
                        list2.add(t);
                    }
                    a++;
                }
                String xx = list2.toString();
                object = list2;
            } else {
                List<BaseTreeconfig> baseTreeconfigLists = redisCacheTreeConfig.getBaseTreeCache(serviceID);
                BaseTreeconfig baseTreeconfig = null;
                BaseTreeconfig baseTreeconfig2 = null;
                String sql = "";
                int as = Integer.parseInt(grade) + 1;
                for (BaseTreeconfig b : baseTreeconfigLists) {
                    if (b.getGrade() == as) {
                        baseTreeconfig = b;
                    }
                    if (b.getGrade() == as + 1) {
                        baseTreeconfig2 = b;
                    }
                }
                if (baseTreeconfig != null) {
                    BaseQuerysql baseQuerysql = selectQuerySql(serviceID, as);
                    String sqlconquery = "";
                    if (baseQuerysql != null) {
                        sqlconquery = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapsts);
                    }
                    CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());

                    sql = "SELECT " + baseTreeconfig.getFieldKey() + " " + "AS ID," + " " + baseTreeconfig.getFieldShow()
                            + " " + "AS NAME," + "'" + id + "'" + "AS PID FROM " + cfgTable.getDtName() + " "
                            + "WHERE 1=1 AND  " + baseTreeconfig.getFieldPKey() + " = '" + id + "'" + sqlconquery;
                }
                sqlList.add(sql);
                List<TreeConfig> list = new ArrayList<>();
                List<Map<String, Object>> list2 = executequerySql(cfgDb, sql);
                for (Map<String, Object> m : list2) {
                    TreeConfig treeConfig = new TreeConfig();
                    treeConfig.setId((String) m.get("ID"));
                    treeConfig.setName((String) m.get("NAME"));
                    treeConfig.setGrade(Integer.parseInt(grade) + 1);
                    treeConfig.setPid("1");
                    if (baseTreeconfig2 == null) {
                        treeConfig.setIsParent(false);
                    } else {
                        treeConfig.setIsParent(true);
                    }
                    list.add(treeConfig);
                }
                object = list;
            }


//			final String sessionID = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
//					.getRequest().getSession().getId();
//			long serverEndTime = System.currentTimeMillis();
//			long serverInterval = serverEndTime - serverStartTime;
//			long sqlInterval = 0;
//			if (TimePushActivemq.getPushSwitch() == 0 && (serverInterval >= TimePushActivemq.getTimeInterval()
//					|| sqlInterval >= TimePushActivemq.getTimeInterval())) {
//				final ServerStatistics server = new ServerStatistics();
//				server.setServerName(serviceID);
//				server.setSql(JSON.toJSONString(sqlList));
//				server.setServerTime(serverInterval);
//				server.setSqlTime(sqlInterval);
//				amqpTemplate.convertAndSend("serverTimeDestination", JSON.toJSONString(server));
//				jmsTemplate.send(destination, new MessageCreator() {
//
//					@Override
//					public Message createMessage(Session session) throws JMSException {
//						FileWriterUtil.saveAsFileWriter(sessionID, JSONObject.fromObject(server).toString());
//						return session.createTextMessage(JSON.toJSONString(server));
//					}
//				});
//			}
        } catch (Exception e) {
            throw new BaseException(e, getSysException());
        }
        return object;
    }

    public Map<String, SysException> getSysException() {
        List<Map<String, Object>> lists = null;
        Map<String, SysException> map = new HashMap<>();
        List<SysException> list = extSysExceptionMapper.selectAllList();
        for (SysException sysException : list) {
            map.put(sysException.getExceptionName(), sysException);
        }
        return map;
    }
}
